$(function(){


    //下面这封装好的函数是获取URL中参数值的方法:
    (function($){
        $.getUrlParam = function(name)
        {
            var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r!=null) return unescape(r[2]); return null;
        }
    })(jQuery);

    //双击已经上传的图片....将图片删除
    $(document).on('dblclick','.putImg img',function(){
        if( confirm('确定删除图片吗?') )
        {//确定删除
            var source = $(this).attr('src');
            var afterCut = source.slice(address.length) + ',';
            var hidden_val = $(this).parent('div').siblings('label').children('input[type = hidden]').val();
            var perfect = hidden_val.split(afterCut).join('');
            $(this).parent('div').siblings('label').children('input[type = hidden]').val(perfect);
            $(this).remove();//从前端展示的页面当中去掉这张图片
        }
        else
        {//取消删除
            // alert(2)
        };

    });

    //页面初始化,,,将省份初始化...产地.....要用到获取省这个接口...
    function getPlaceOfOrigin()
    {
        $.ajax({
            type:'get',
            async:false,
            headers: {"Accept-CMS-Token":token},
            url:provincelist,
            dataType:'json',
            data:{},
            success:function (data){
                if(data.resultCode == 200)
                {
                    var value = data.value;
                    var str = '';
                    for( var i = 0;i<value.length;i++ )
                    {
                        str+='<option value="'+value[i].id+'">'+value[i].fullName+'</option>'

                    }
                    $('.place_of_origin').append(str);
                    console.log('获取省接口调通!!!!');
                }
                else if(data.resultCode == 515)
                {
                    reLogin();
                }
            },
            error:function(){
                console.log('获取省接口请求失败');
            },
        });
    };
    getPlaceOfOrigin();

    //根据省查询市.......
    function getCity( provinceId )
    {
        $.ajax({
            type:'get',
            headers: {"Accept-CMS-Token":token},
            url:findcitybyprovinceid,
            async:false,
            dataType:'json',
            data:{
                provinceId:provinceId
            },
            success:function (data){
                if(data.resultCode == 200)
                {
                    var value = data.value;
                    var str = '';
                    for( var i = 0;i<value.length;i++ )
                    {
                        str+='<option value="'+value[i].id+'">'+value[i].fullName+'</option>'

                    };
                    $('.city').html('');
                    $('.city').append(str);
                    console.log('根据省查询市接口调通!!!!');
                }
                else if(data.resultCode == 515)
                {
                    reLogin();
                }
            },
            error:function(){
                console.log('根据省查询市接口请求失败');
            },
        });
    };

    // 当place_of_origin这个change时....在调用根据省查询市这个接口,,,获取这个省对应的城市.....
    $('.place_of_origin').change(function(){

        provinceId = $('.place_of_origin option:selected').val();

        getCity( provinceId );
    });

    //获取规格标签列表
    function setGuiGe(commodityNumber)
    {
        $.ajax({
            type:'post',
            async:false,
            headers: {"Accept-CMS-Token":token},
            url:finddictlist,
            dataType:'json',
            data:{
                commodityNumber:commodityNumber,
                type:1
            },
            success:function (data){
                if(data.resultCode == 200)
                {
                    var standard = data.value;
                    var len = standard.length;
                    var str='';
                    for( var i=0;i<len;i++ )
                    {
                        str+='<option value="'+standard[i].id+'">'+standard[i].name+'</option>';
                    };
                    $('.guiGe').append(str);
                    console.log('获取标签列表接口调通!!!!')
                }
                else if(data.resultCode == 515)
                {
                    reLogin();
                }
            },
            error:function(){
                console.log('获取标签列表接口请求失败')
            },
        });
    };
    setGuiGe('123');

    // 页面初始化....将这个商品的id传递到函数当中获取接口中的数据...
    showData( $.getUrlParam('commondityId') );

    // 封装好的一个函数,,,用来回显接口当中的数据到页面当中........
    function showData(commondityId)
    {

        $.ajax({
            type:'post',
            async:false,
            headers: {"Accept-CMS-Token":token},
            url:shopcommondityone,
            dataType:'json',
            data:{
                commondityId:commondityId
            },
            success:successFn,
            error:function(){
                console.log('获取省接口请求失败');
            },
        });

    };

    // 调回显数据的接口请求成功之后,,,执行此函数...
    function successFn(data)
    {
        if(data.resultCode == 200)
        {
            var value = data.value.shopCommodity;

            // 将后台返回来的数据取其中一条...回显到页面当中...
            $('input[name = number]').val( value.number );
            $('input[name = name]').val( value.name );
            $('input[name = price]').val( value.price );
            $('input[name = totalNum]').val( value.totalNum );
            $('input[name = modelName]').val( value.modelName );
            $('input[name = company]').val( value.company );
            //回显颜色中的数据
            $('.getColor').append('<dd class="fl project_width"><label><input type="radio" name="color" value="'+value.colorId+'" class="project" description="'+value.colorName+'" checked>'+value.colorName+'</label></dd>');
            // 回显尺寸当中的数据
            $('.getSize').append('<dd class="fl project_width"><label><input type="radio" name="size" value="'+value.sizeId+'" class="project" description="'+value.sizeName+'" checked>'+value.sizeName+'</label></dd>');

            // 标签回显
            var lableIdArr = value.lableId.split(',');
            var lableNameArr = value.lableName.split(',');
            if(lableIdArr.length == 1)
            {
                $('.getTag').append('<dd class="fl project_width"><label><input type="checkbox" name="tag" value="'+lableIdArr[0]+'" class="project" description="'+lableNameArr[0]+'" checked>'+lableNameArr[0]+'</label></dd>');
            }
            else
            {
                for(var m=0;m<(lableIdArr.length-1);m++)
                {
                    $('.getTag').append('<dd class="fl project_width"><label><input type="checkbox" name="tag" value="'+lableIdArr[m]+'" class="project" description="'+lableNameArr[m]+'" checked>'+lableNameArr[m]+'</label></dd>');
                };
            };
            // console.log(lableIdArr)
            //状态回显
            if( value.status == 1 )
            {
                $('.status option').eq(1).attr( 'selected','selected' );
            }
            else
            {
                $('.status option').eq(2).attr( 'selected','selected' );
            };
            // 产地----省回显
            for( var i=0;i<$('.place_of_origin option').length;i++ )
            {
                if( $('.place_of_origin option').eq(i).val() == value.areaProvinceId )
                {
                    $('.place_of_origin option').eq(i).attr( 'selected','selected' );
                    break;
                };
            };
            getCity( value.areaProvinceId );
            // 产地-----市回显
            for( var j=0;j<$('.city option').length;j++ )
            {
                if( $('.city option').eq(j).val() == value.areaCityId )
                {
                    $('.city option').eq(j).attr( 'selected','selected' );
                    break;
                };
            };
            // 规格回显
            for( var q=0;q<$('.guiGe option').length;q++ )
            {
                if( $('.guiGe option').eq(q).val() == value.specificationId )
                {
                    $('.guiGe option').eq(q).attr( 'selected','selected' );
                    break;
                }
            };
            $('.wrap_fengMian div div img').attr( 'src',address + value.coverUrl );
            $('.wrap_fengMian div div img').attr( 'height',300 );
            $('input[name = coverUrl]').val( value.coverUrl );
            // 图文详情回显数据...
            var imgDetailArr = value.commodityDetailImgUrl.split(',');
            if(imgDetailArr.length == 1)
            {
                $('.wrap_datail div div').append('<img src="'+address + imgDetailArr[0]+'" width="230" height="150">');
                $('input[name = detailUrl]').val( imgDetailArr[0] );
            }
            else
            {
                var saveDetailStr = '';
                for( var x=0;x<(imgDetailArr.length);x++ )
                {
                    $('.wrap_datail div div').append('<img src="'+address + imgDetailArr[x]+'" width="230" height="150">');
                    saveDetailStr = saveDetailStr + imgDetailArr[x] + ',';
                };
                $('input[name = detailUrl]').val( saveDetailStr );
            };
            $('input[name = detailUrl]').val( value.detailUrl );
            // 产品参数回显数据
            var base = new Base64();
                var commodity = JSON.parse( base.decode(value.commodity) ) ;
                for( var key in commodity ){

                $('.productPara tbody').append( '<tr><th><input type="text" value="'+ key +'" class="font_white param_name" placeholder="请输入"></th><td><input type="text" value="' + commodity[key] + '" placeholder="请输入" class="param_value"></td></tr>' );

            };

            // textarea数据回显
            $('textarea[name = info]').val( value.info );
            $('textarea[name = packingList]').val( value.packingList );
            $('textarea[name = afterSalesService]').val( value.afterSalesService );
            $('textarea[name = useing]').val( value.useing );

            console.log('获取省接口调通!!!!');
        }
        else if(data.resultCode == 515)
        {
            reLogin();
        }
    };

    //点击保存,,,将整个页面的信息都保存提交给后台,,,并跳转到智能硬件的页面
    $('.save_add_intelligence').click(function(){
        // 验证表单的text,,,radio,,,和select,,,hidden,,textarea不能为空
        var text = $('.shop_info input[type = text]');
        var number = $('.shop_info input[type = number]');

        // 验证text不能为空
        for(var i = 0;i<text.length;i++)
        {
            if(text.eq(i).val() == '')
            {
                $(text).eq(i).after('<span class="tips">*不能为空</span>');
                return false;
            }
            else
            {
                $(text).eq(i).siblings('span').html('');
            };
        };

        // 验证number输入框不能为空
        for(var i = 0;i<number.length;i++)
        {
            if(number.eq(i).val() == '')
            {
                $(number).eq(i).after('<span class="tips">*不能为空</span>');
                return false;
            }
            else
            {
                $(number).eq(i).siblings('span.tips').html('');
            };
        };

        //验证radio不能为空       color不能为空....
       /* if( $('.shop_info input[name = color]:checked').val() == undefined )
        {
            $('.getColor').append('<dd class="fl project_width span_tips"><span class="tips">*不能为空</span></dd>');
            return false;
        }
        else
        {
            $('.getColor').children('dd.span_tips').html('');
        };
        //验证radio不能为空       size不能为空....
        if( $('.shop_info input[name = size]:checked').val() == undefined )
        {
            $('.getSize').append('<dd class="fl project_width span_tips"><span class="tips">*不能为空</span></dd>');
            return false;
        }
        else
        {
            $('.getSize').children('dd.span_tips').html('');
        };

        //验证select不能为空      status不能为空
        if( $('.status option:selected').val() == 0 )
        {
            $('.status').after('<span class="tips" style="margin:0 0 0 10px;">*不能为空</span>');
            return false;
        }
        else
        {
            $('.status').parent('dd').children('span.tips').html('');
        };
        //验证select不能为空      place_of_origin不能为空
        if( $('.place_of_origin option:selected').val() == 0 )
        {
            $('.place_of_origin').parent('label').append('<span class="tips">*不能为空</span>');
            return false;
        }
        else
        {
            $('.place_of_origin').parent('label').children('span.tips').html('');
        };
        //验证select不能为空      city不能为空
        if( $('.city option:selected').val() == 0 )
        {
            $('.city').parent('label').append('<span class="tips">*不能为空</span>');
            return false;
        }
        else
        {
            $('.city').parent('label').children('span.tips').html('');
        };

        //验证select不能为空      guiGe不能为空
        if( $('.guiGe option:selected').val() == 0 )
        {
            $('.guiGe').after('<span class="tips" style="margin:0 0 0 10px;">*不能为空</span>');
            return false;
        }
        else
        {
            $('.guiGe').parent('dd').children('span.tips').html('');
        };*/
        //上传图片不能为空      coverUrl不能为空
        if( $('input[name = coverUrl]').val() == '')
        {
            $('input[name = coverUrl]').parent('label').after('<span class="tips picTips" style="margin:0 0 0 10px;">*不能为空</span>');
            return false;
        }
        else
        {
            $('input[name = coverUrl]').parent('label').siblings('span.picTips').html('');
        };
        //上传图片不能为空      detailUrl不能为空
        if( $('input[name = detailUrl]').val() == '')
        {
            $('input[name = detailUrl]').parent('label').after('<span class="tips picTips" style="margin:0 0 0 10px;">*不能为空</span>');
            return false;
        }
        else
        {
            $('input[name = detailUrl]').parent('label').siblings('span.picTips').html('');
        };
        //上传图片不能为空      parameterUrl不能为空
        if( $('input[name = parameterUrl]').val() == '')
        {
            $('input[name = parameterUrl]').parent('label').after('<span class="tips picTips" style="margin:0 0 0 10px;">*不能为空</span>');
            return false;
        }
        else
        {
            $('input[name = parameterUrl]').parent('label').siblings('span.picTips').html('');
        };
        // 验证textarea的内容不能为空
        // var textarea = $('.ctrlPadding textarea');
        // for( var j=0;j<textarea.length;j++ )
        // {
        //     if( textarea.eq(j).val() == '' )
        //     {
        //         $(textarea).eq(j).after('<span class="tips textareaTips" style="margin:0 0 0 10px;">*不能为空</span>');
        //         return false;
        //     }
        //     else
        //     {
        //         $(textarea).eq(j).parent('dd').children('span.textareaTips').html('');
        //     };
        // };
        //向后台发送请求!!!
        sendAjax();
    });

    // 封装好的函数向后台传递参数,,,当发送成功以后跳转整个页面
    function sendAjax()
    {
        var lableIdStr = '';
        var lableNameStr = '';
        //获取被选中的checkbox....
        for( var i=0;i<$('input[name = tag]:checked').length;i++ )
        {
            lableIdStr = lableIdStr + $('input[name = tag]:checked').eq(i).val() + ',';
            lableNameStr = lableNameStr + $('input[name = tag]:checked').eq(i).attr('description') + ',';
        };

        // 获取用户自定义的产品参数
        var commodity , commodity_json = {};
        var len = $('.param_name').length;
        for( var i = 0;i<len;i++ ){

            if( $('.param_name').eq(i).val() != '' ){

                commodity_json[ $('.param_name').eq(i).val() ] = $('.param_value').eq(i).val();

            };

        };
        commodity = JSON.stringify(commodity_json);

        var base = new Base64();


        $.ajax({
            type:'post',
            async:false,
            headers: {"Accept-CMS-Token":token},
            url:saveshopcommondity,
            dataType:'json',
            data:{
                // 产品参数
                commodity:base.encode(commodity),
                // 页面当中其他部分的信息
                afterSalesService:$('textarea[name = afterSalesService]').val(),
                alias:'',
                areaCityId:$('.city option:selected').val(),
                areaCityName:$('.city option:selected').html(),
                areaProvinceId:$('.place_of_origin option:selected').val(),
                areaProvinceName:$('.place_of_origin option:selected').html(),
                categoryIdcategoryId:'',
                categoryNameL:'',
                colorId:$('input[name = color]:checked').val(),
                colorName:$('input[name = color]:checked').attr('description'),
                company:$('input[name = company]').val(),
                coverUrl:$('input[name = coverUrl]').val(),
                detailUrl:$('input[name = detailUrl]').val(),
                directions:'',
                effect:'',
                info:$('textarea[name = info]').val(),
                lableId:lableIdStr,
                lableName:lableNameStr,
                machining:'',
                meridian:'',
                modelName:$('input[name = modelName]').val(),
                name:$('input[name = name]').val(),
                number:$('input[name = number]').val(),
                packingList:$('textarea[name = packingList]').val(),
                parameterUrl:$('input[name = parameterUrl]').val(),
                position:'',
                price:$('input[name = price]').val(),
                publicCommodityHardUrl:'',
                publicCommodityMedicineUrl:'',
                shape:'',
                sizeId:$('input[name = size]:checked').val(),
                sizeName:$('input[name = size]:checked').attr('description'),
                specificationId:$('.guiGe option:selected').val(),
                specificationName:$('.guiGe option:selected').html(),
                status:$('.status option:selected').val(),
                taboo:'',
                taste:'',
                totalNum:$('input[name = totalNum]').val(),
                type:1,
                useing:$('textarea[name = useing]').val(),
                commondityId:$.getUrlParam('commondityId')
            },
            success:function (data){
                if(data.resultCode == 200)
                {
                    alert('保存成功!');
                    window.location.href = shangpin_admin;
                    console.log('添加智能硬件接口调通!!!!');
                }
                else if(data.resultCode == 515)
                {
                    reLogin();
                }
            },
            error:function(){
                console.log('添加智能硬件接口请求失败');
            },
        });

    };

    //点击添加颜色的标签出现弹框
    $('.add_color_tag').click(function(){
        showBounce('.add_color_bounce');
    });

    // 点击添加尺寸的标签出现弹框
    $('.add_size_tag').click(function(){
        showBounce('.add_size_bounce');
    });

    // 点击添加标签,,出现弹框
    $('.add_tag_tag').click(function(){
        showBounce('.add_tag_bounce');
    });

    //出现弹框的一个函数
    function showBounce(Dom)
    {
        $('.mask-change').show()
        $(Dom).show();
        $(Dom).children('div').children('input').focus();
    };

    //点击确定添加颜色,,,将标签的名字传递到后台....前端的页面当中增加一个对应的标签
    $('.sure_add_color').click(function(){

        addTag('.color_val',2,'.add_color_tag','color');

    });

    // 点击确定添加尺寸,,,将标签的名字传递给后台,,,前端的页面当中增加一个对应的标签
    $('.sure_add_size').click(function(){

        addTag('.size_val',3,'.add_size_tag','size');

    });

    // 点击确定添加代表标签,,,将标签的名字传递给后台,,,,前端的页面当中增加一个对应的标签
    $('.sure_add_tag').click(function(){

        addCheckBoxTag('.tag_val',4,'.add_tag_tag','tag');

    });

    //添加标签,,,页面中出现复选框,,,前端增加,,
    function addCheckBoxTag(input,type,Dom,name)
    {
        var input_val = $(input).val();
        if( input_val == '' )
        {
            alert('输入不能为空!')
        }
        else
        {
            $.ajax({
                type:'get',
                headers: {"Accept-CMS-Token":token},
                url:savedict,
                dataType:'json',
                data:{
                    name:input_val,
                    type:type
                },
                success:function (data){
                    if(data.resultCode == 200)
                    {
                        $(Dom).parent('div').siblings('dl').append('<dd class="fl project_width"><label><input type="checkbox" name="'+name+'" value="'+data.value.id+'" class="project" description="'+data.value.name+'" checked>'+data.value.name+'</label></dd>');
                        // alert('添加成功!');
                        $('.mask-change').hide()
                        $('.add_option').hide();
                        console.log('添加标签接口调通!!!!');
                    }
                    else if(data.resultCode == 515)
                    {
                        reLogin();
                    }
                },
                error:function(){
                    console.log('添加标签接口请求失败');
                },
            });
            $(input).val('');
        };
    };

    //添加标签,,,前端添加,,,,添加颜色,尺寸都调用这个封装好的函数     添加标签被单拎了出来
    function addTag(input,type,Dom,input_name)
    {
        var input_val = $(input).val();
        if( input_val == '' )
        {
            alert('输入不能为空!')
        }
        else
        {
            $.ajax({
                type:'get',
                headers: {"Accept-CMS-Token":token},
                url:savedict,
                dataType:'json',
                data:{
                    name:input_val,
                    type:type
                },
                success:function (data){
                    if(data.resultCode == 200)
                    {
                        $(Dom).parent('div').siblings('dl').append('<dd class="fl project_width"><label><input type="radio" name="'+input_name+'" value="'+data.value.id+'" class="project" description="'+data.value.name+'" checked>'+data.value.name+'</label></dd>');
                        // alert('添加成功!');
                        $('.mask-change').hide()
                        $('.add_option').hide();
                        console.log('添加标签接口调通!!!!');
                    }
                    else if(data.resultCode == 515)
                    {
                        reLogin();
                    }
                },
                error:function(){
                    console.log('添加标签接口请求失败');
                },
            });
            $(input).val('');
        };
    };

    //上传封面图片    只能上传一张图片...
    $('.upload_fengMian').change(function(){

        upLoadOnePic(1,'.upload_fengMian','input[name = coverUrl]','.wrap_fengMian');

    });

    //上传图文详情图片  可以支持多张图片
    $('.upload_detail').change(function(){

        upLoadMoreDetailPic('.upload_detail','input[name = detailUrl]','.wrap_datail');

    });

    //上传图片封装好的函数    只能上传一张图片
    function upLoadOnePic(type,Dom_input,input_hidden,wrap_form)
    {
        var option={
            type: "post",
            headers: {"Accept-CMS-Token":token},
            url: saveshopimage,
            data: {
                fileName:'fileSize',
                type:type
            },
            dataType:'json',
            async: false,
            error: function(data){
                alert("Connection error");
            },
            success: function(data){
                if(data.resultCode == 200)
                {
                    $(Dom_input).parent('label').siblings('div').children('img').attr('src',address + data.value);
                    $(Dom_input).parent('label').siblings('div').children('img').attr('height',300);
                    $(input_hidden).val(data.value);
                }
                else if(data.resultCode == 515)
                {
                    reLogin();
                }
                else
                {
                    // alert('接口非200,非515,非500')
                };
            }
        };
        $(wrap_form).ajaxSubmit(option);
    };

    //上传图文详情图片...封装好的函数    上传多张图片
    function upLoadMoreDetailPic(Dom_input,input_hidden,wrap_form)
    {
        var option={
            type: "post",
            headers: {"Accept-CMS-Token":token},
            url: savemanyimage,
            data: {
                upfile:'upfile',
                // type:type
            },
            dataType:'json',
            async: false,
            error: function(data){
                alert("Connection error");
            },
            success: function(data){
                if(data.resultCode == 200)
                {
                    var detailStr = $(input_hidden).val();
                    if( detailStr != '' )
                    {
                        detailStr = detailStr + ',';
                    };
                    var newStr = data.value.split(',');
                    for( var i = 0;i<newStr.length;i++ )
                    {
                        $(Dom_input).parent('label').siblings('div').append('<img src="'+address + newStr[i]+'" width="230" height="150">');
                    };
                    detailStr = detailStr + data.value + ',';

                    $(input_hidden).val(detailStr.substring( 0,detailStr.length - 1 ));
                }
                else if( data.resultCode == 515 )
                {
                    reLogin();
                }
                else
                {
                    // alert('接口非200,非515,非500')
                };
            }
        };
        $(wrap_form).ajaxSubmit(option);
    };

    // 点击添加...将产品参数追加到表格后面
    $('span.add_para_table').click(function () {

        $('.productPara tbody').append('<tr><th><input type="text" name="" value="" class="font_white param_name" placeholder="请输入"></th><td><input type="text" value="" placeholder="请输入" class="param_value"></td></tr>');

    });





});
